package com.yzx.controller.system;

import cn.hutool.core.date.DateUtil;
import com.yzx.aspectj.annotation.Log;
import com.yzx.aspectj.enums.BusinessType;
import com.yzx.constants.Constants;
import com.yzx.constants.HttpStatus;
import com.yzx.domain.SysLoginInfo;
import com.yzx.domain.SysMenu;
import com.yzx.dto.LoginBodyDto;
import com.yzx.dto.SimpleUser;
import com.yzx.service.SysLoginInfoService;
import com.yzx.service.SysMenuService;
import com.yzx.utils.AddressUtils;
import com.yzx.utils.IpUtils;
import com.yzx.utils.ShiroSecurityUtils;
import com.yzx.vo.ActiverUser;
import com.yzx.vo.AjaxResult;
import com.yzx.vo.MenuTreeVo;
import eu.bitwalker.useragentutils.UserAgent;
import lombok.extern.log4j.Log4j2;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.aspectj.weaver.loadtime.Aj;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("login")
@Log4j2
public class LoginController {

    @Autowired
    private SysMenuService sysMenuService;
    @Autowired
    private SysLoginInfoService sysLoginInfoService;
    @RequestMapping("doLogin")
//    @Log(title = "用户登录",businessType = BusinessType.OTHER)
    public AjaxResult doLogin(@RequestBody @Validated LoginBodyDto loginBodyDto,HttpServletRequest request){
        AjaxResult ajax=AjaxResult.success();
        String username=loginBodyDto.getUsername();
        String password=loginBodyDto.getPassword();

        UsernamePasswordToken token=new UsernamePasswordToken(username,password);
        Subject subject = SecurityUtils.getSubject();
        SysLoginInfo sysLoginInfo =createLoginInfo(request);
        try {
            subject.login(token);
            Serializable id = subject.getSession().getId();
            ajax.put(Constants.TOKEN,id);
            sysLoginInfo.setMsg("登录成功");
            sysLoginInfo.setLoginStatus(Constants.LOGIN_SUCCESS);
            sysLoginInfo.setUserName(ShiroSecurityUtils.getCurrentUserName());
            sysLoginInfo.setLoginAccount(loginBodyDto.getUsername());
            sysLoginInfo.setLoginTime(DateUtil.date());
        }catch (Exception ex){
            log.error("用户名密码错误",ex);
            sysLoginInfo.setMsg("登录失败");
            sysLoginInfo.setLoginStatus(Constants.LOGIN_ERROR);
            sysLoginInfo.setUserName("登录失败用户");
            sysLoginInfo.setLoginAccount(loginBodyDto.getUsername());
            sysLoginInfo.setLoginTime(DateUtil.date());
            ajax=AjaxResult.error(HttpStatus.ERROR,"用户名或者密码错误");
        }
        sysLoginInfoService.insertLoginInfo(sysLoginInfo);
        return ajax;
    }

    private SysLoginInfo createLoginInfo(HttpServletRequest request) {
        SysLoginInfo sysLoginInfo = new SysLoginInfo();
        UserAgent userAgent = UserAgent.parseUserAgentString(request.getHeader("User-Agent"));
        String ip= IpUtils.getIpAddr(request);
        String address= AddressUtils.getRealAddressByIP(ip);
        String os=userAgent.getOperatingSystem().getName();
        String browser=userAgent.getBrowser().getName();
        sysLoginInfo.setIpAddr(ip);
        sysLoginInfo.setLoginLocation(address);
        sysLoginInfo.setOs(os);
        sysLoginInfo.setBrowser(browser);
        sysLoginInfo.setLoginType(Constants.LOGIN_TYPE_SYSTEM);
        return sysLoginInfo;
    }

    @GetMapping("getInfo")
    public AjaxResult getInfo(){
        Subject subject = SecurityUtils.getSubject();
        ActiverUser activerUser= (ActiverUser) subject.getPrincipal();
        AjaxResult ajax = AjaxResult.success();
        ajax.put("username", activerUser.getUser().getUserName());
        ajax.put("picture", activerUser.getUser().getPicture());
        ajax.put("roles", activerUser.getRoles());
        ajax.put("permissions", activerUser.getPermissions());
        return ajax;
    }
    @PostMapping("logout")
//    @Log(title = "用户退出",businessType = BusinessType.OTHER)
    public AjaxResult logout(){
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return AjaxResult.success();
    }

    @GetMapping("getMenus")
    public AjaxResult getMeuns()
    {
        Subject subject = SecurityUtils.getSubject();
        ActiverUser activerUser= (ActiverUser) subject.getPrincipal();
        boolean isAdmin=activerUser.getUser().getUserType().equals(Constants.USER_ADMIN);
        SimpleUser simpleUser=null;
        if(!isAdmin){
            simpleUser=new SimpleUser(activerUser.getUser().getUserId(),activerUser.getUser().getUserName());
        }
        List<SysMenu> menus = sysMenuService.selectMenuTree(isAdmin,simpleUser);
        List<MenuTreeVo> menuVos=new ArrayList<>();
        for (SysMenu menu : menus) {
            menuVos.add(new MenuTreeVo(menu.getMenuId().toString(),menu.getPath()));
        }
        return AjaxResult.success(menuVos);
    }

    @GetMapping("dynamicMenu")
    @Log(title = "动态菜单",businessType = BusinessType.OTHER)
    public List<Map<String, Object>> dynamicMenu()
    {
//        System.out.println(10/0);
        List<Map<String, Object>> list=sysMenuService.dynamicMenu();
//        List<Map<String, Object>> list = new ArrayList<>();
        return list;
    }
}
